package com.zpl.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author wangyuxin
 * @date 2020/10/2
 */
@Component
public class COSStorage {
    private COSClient cosClient;
    private  String secretId = "AKIDHNHzinSZjRekaHsEXZPyHNEohMp2doPJ";
    private  String secretKey = "oMecBFVWodqFSqnIpB9tzve7oE9PRN3T";
    private  String regionStr = "ap-beijing";
    private  String bucketName = "zpl-1303223223";
    /**
     * 获取一个COSClient对象
     */
    public COSStorage(){
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(regionStr);
        ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }


    /**
     * 创建存储桶
     */

    public Bucket createBucket(String bucketName){
        //String bucket = "examplebucket-1250000000"; //存储桶名称，格式：BucketName-APPID
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
// 设置 bucket 的权限为 PublicRead(公有读私有写), 其他可选有私有读写, 公有读写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        try{
            return cosClient.createBucket(createBucketRequest);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
        return null;
    }
    /**
     * 文件上传
     */
    public  String upload(String path){
        //查询桶名
        List<Bucket> buckets =cosClient.listBuckets();
        boolean isBucket=false;
        for (Bucket bucketElement : buckets){
            if(bucketName.equals(bucketElement.getName())){
                isBucket=true;
            }
            // String bucketLocation = bucketElement.getLocation();
        }
        if (!isBucket){
            createBucket(bucketName);
        }
        // 指定要上传到 COS 上对象键
        Date date = new Date();
        String key ="/ad/" + date.getTime()+"";
        File localFile = new File(path);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        String imagePath = "https://"+bucketName+".cos."+regionStr+".myqcloud.com"+key;
        return imagePath;
    }

    /**
     * 图片删除
     */

    public void delete(String path){
        //查询桶名
        List<Bucket> buckets =cosClient.listBuckets();
        boolean isBucket=false;
        for (Bucket bucketElement : buckets){
            if(bucketName.equals(bucketElement.getName())){
                isBucket=true;
            }
            // String bucketLocation = bucketElement.getLocation();
        }
        if (!isBucket){
            System.out.println("指定文件不存在");
        }
        //如何从path里面查找到key
        String key = path.substring(50);
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName,key);
        cosClient.deleteObject(deleteObjectRequest);
    }
}
